const Router = require('koa-router')
const mysql = require('../util/mysql/mysql')
const { SUCCESS, PARAM_NOT_COMPLETE, FAIL } = require('../util/respone/index')

let product = new Router()

function checkForm(params,checkType = '*') {
  // 拼接 查询数据库语句 
  let { id, name = '', tags = '' } = params
  let checkProduct = '', checkComments = '';
  if (id) {
    // 查询 该id的产品
    checkProduct = `SELECT ${checkType} FROM product WHERE id = ${id}`

    // 查询 该id的产品中的评论
    checkComments = `SELECT comments.* FROM product INNER join comments on comments.c_id = product.id where product.id = ${id}`

    // 查询 该id的产品中的问题
    checkQuestions = `SELECT questions.* FROM product INNER join questions on questions.p_id = product.id where product.id = ${id}`

    return { checkProduct, checkComments, checkQuestions }
  } else if (name || tags) {
    // 模糊查询 产品的名称和标签
    return { checkProduct: `SELECT ${checkType} FROM product WHERE name LIKE '%${name}%' and tags LIKE '%${tags}%'` }
  } else {
    // 查询所有产品
    return { checkProduct: `SELECT ${checkType} FROM product`}
  }
}

// 获取产品信息
product.get('/product', async (ctx, next) => {
  // 用户post过来的数据
  let { id = null, pageSize = 10, pageNum = 1} = ctx.query;

  // 拼接 查询数据库 语句
  let checkSql = checkForm(ctx.query).checkProduct + ` limit ${(pageNum - 1) * pageSize}, ${pageSize}`
  

  // 拼接 查询总数 语句
  let checkTotalSql = checkForm(ctx.query,'COUNT(*)').checkProduct
  
  let outObj = { pageSize, pageNum }; // 向外输出数据的obj
  let isSuccess = true; // 数据库中 查询操作成功标签
  // -------数据库操作------
  // 查询数据库中数据
  await mysql.check(checkSql)
    .then(async res => {
      outObj.dataList = res
    })
    .catch(async err => {
      isSuccess = false
      return await FAIL(ctx, '查询"产品信息"出错!')
    })
  
  if(!isSuccess) return // 如果查询出错则不需要执行下面查询
  
  // 如果 接收到id 则查询产品的评论
  if (id) {
    let checkSqlComment = checkForm(ctx.query).checkComments
    await mysql.check(checkSqlComment)
      .then(async res => {
        outObj.dataList[0]['comments'] = res
      })
      .catch(async err => {
        isSuccess = false
        return await FAIL(ctx,'查询"产品评论"出错!')
      })
    
    let checkQuestions = checkForm(ctx.query).checkQuestions
    await mysql.check(checkQuestions)
      .then(async res => {
        outObj.dataList[0]['questions'] = res
      })
      .catch(async err => {
        isSuccess = false
        return await FAIL(ctx,'查询"产品问题"出错!')
      })
  }
  
  if(!isSuccess) return // 如果查询出错则不需要执行下面查询

  //查询总数
  await mysql.check(checkTotalSql)
    .then(async res => {
      outObj.total = res[0]['COUNT(*)']
    })
    .catch(async err => {
      isSuccess = false
      return await FAIL(ctx,'查询"产品总数"出错!')
    })
    
  if (isSuccess) {
    await SUCCESS(ctx,outObj,"获取产品成功！")
  }
})

// 添加产品
product.post('/product', async (ctx, next) => {
  // 用户post过来的数据
  let { name,introduction,details,tags,technology,service,bImg,sImg1,sImg2 } = ctx.request.body;

  // -------数据库操作------
  let addSql = 'INSERT INTO product(name,introduction,details,tags,technology,service,bImg,sImg1,sImg2) VALUES(?,?,?,?,?,?,?,?,?)'
  let addSqlParams = [name, introduction, details, tags, technology, service, bImg, sImg1, sImg2]
  await mysql.add(addSql, addSqlParams)
    .then(async res => {
      await SUCCESS(ctx,{},"添加产品成功！")
    })
    .catch(async err => {
      return await FAIL(ctx,'添加产品出错!')
  })
})

// 删除产品
product.delete('/product', async (ctx, next) => {
  let { id } = ctx.request.body

  if (!id) { // 如果没有传入id 则弹出 错误：请求参数缺失
    return await PARAM_NOT_COMPLETE(ctx)
  }
  
  // -----数据库操作-------
  let delSql = `DELETE FROM product WHERE id = "${id}"`
  await mysql.delete(delSql)
    .then(async res => {
      await SUCCESS(ctx, {}, "删除产品成功！")
    })
    .catch(async err => {
      return await FAIL(ctx, '添加产品出错!')
    })
})

// 修改产品信息
product.put('/product', async (ctx, next) => {
  let putParams = ctx.request.body;

  if (!putParams.id) { // 如果没有传入id 则弹出 错误：请求参数缺失
    return await PARAM_NOT_COMPLETE(ctx)
  }

  // 拼接 修改产品信息的 key值
  let keysArr = Object.keys(putParams)
  let template = keysArr.join(' = ?, ') + ' = ? '

  // -----数据库操作-------
  let updateSql = 'UPDATE product SET ' + template + 'WHERE id = ?'
  let updateSqlParams = Object.values(putParams)
  updateSqlParams.push(putParams.id)

  await mysql.update(updateSql, updateSqlParams)
    .then(async res => {
    await SUCCESS(ctx,{},"修改产品信息成功!")
    })
    .catch(async err => {
      return await FAIL(ctx, '修改产品信息出错!')
  })
})

module.exports = { product }